import re
from django import forms
from .models import User

class ContactForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['truename', 'phone', 'company_name','company_address']

        def clean_mobile(self):  # 函数必须以clean_开头
            """
            通过正则表达式验证手机号码是否合法
            """
            phone = self.cleaned_data['phone']
            phone_regex = r'^1[34578]\d{9}$'
            p = re.compile(phone_regex)
            if p.match(phone):
                return phone
            else:
                raise forms.ValidationError('手机号码非法', code='invalid mobile')